using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

namespace Unity.Per.Common.UIFrameWork {

    public class BindWindow :BaseModuleMono,IPointerDownHandler
    {
        public RectTransform WindowRegion;

        public bool IsOpen = false;

        [SerializeField]
        private BaseWindow windowprefab;

        private BaseWindow m_windowInstance;
        public BaseWindow windowInstance {
            get {
                if ( windowprefab == null )
                    return null;

                if ( m_windowInstance == null ) {
                    m_windowInstance = Instantiate<BaseWindow>(windowprefab);
                    m_windowInstance.bindWindow = this;

                    if ( WindowRegion ) {
                       m_windowInstance.transform.SetParent(WindowRegion,false);
                    }
                }
                return m_windowInstance;
            }
        }


        [SerializeField]
        private BaseWindowSlot m_windowSlot;
        public BaseWindowSlot windowSlot {
            get {
                if ( m_windowSlot == null ) {
                    UpdateBaseWindowSlot(GetComponentInParent<BaseWindowSlot>());
                }
                return m_windowSlot;
            }
            set {
                UpdateBaseWindowSlot(value);
            }
        }

        void UpdateBaseWindowSlot(BaseWindowSlot baseWindowSlot) {
            if ( baseWindowSlot == m_windowSlot )
                return;

            if ( m_windowSlot ) {
                m_windowSlot.RemoveModule(this);
                m_windowSlot.RemoveBindWindow(this);
            }

            m_windowSlot = baseWindowSlot;

            if ( m_windowSlot ) {
                m_windowSlot.AddModule(this);
                m_windowSlot.AddBindWindow(this);
            }
        }



        /// <summary>
        /// Open Window
        /// </summary>
        protected override void OnModuleStart() {
            base.OnModuleStart();
            if ( windowSlot && windowInstance ) {
                windowInstance.ModuleStart();
            }
        }

        /// <summary>
        /// Close Window
        /// </summary>
        protected override void OnModuleStop() {
            base.OnModuleStop();
            if ( windowSlot && windowInstance ) {
                windowInstance.ModuleStop();
            }
        }



        public void OnPointerDown(PointerEventData eventData) {
            if ( windowSlot == null )
                return;

            if ( windowSlot.CurrentBindWindow == this ) {
                windowSlot.Close();
            } else {
                windowSlot.Open(this);
            }
        }
    }

}